package com.hqq.helper;

import com.hqq.annotation.Inject;
import com.hqq.util.ReflectionUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * IoCHelper
 * 依赖注入帮助类
 * 思路:
 * 从BeanHelper[Bean容器]中遍历所有的类,如果当前对象的某个字段存在@Inject注解，则从容器中取出bean实例注入到属性中
 * Created by heqianqian on 2017/7/19.
 */
public class IoCHelper {

    public static void init() {
        //获取Bean容器中所有的bean
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        for (Map.Entry<Class<?>, Object> entry : beanMap.entrySet()) {
            Class<?> beanClass = entry.getKey();
            Object object = entry.getValue();
            Field[] fields = beanClass.getDeclaredFields();
            if (!ArrayUtils.isEmpty(fields)) {
                for (Field f : fields) {
                    if (f.isAnnotationPresent(Inject.class)) {
                        Class<?> injectObjectType = f.getType();
                        Object instance = beanMap.get(injectObjectType);
                        if (instance != null) {
                            ReflectionUtil.setField(object, f, instance);
                        }
                    }
                }
            }
        }
    }
}
